#include <QComboBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QTextCodec>
#include <QKeyEvent>

#include "QyCodecDialog.h"

QyCodecDialog::QyCodecDialog( QWidget * parent ) : QDialog(parent) {

	QHBoxLayout * layout = new QHBoxLayout(this);
	QLabel * label = new QLabel( tr("Encoding:"), this );
	codecBox = new QComboBox(this);

	layout->addWidget(label);
	layout->addWidget(codecBox);

	setWindowTitle( tr("Choose encoding") );

}

void QyCodecDialog::fillComboBox( QComboBox * comboBox ) {

	QList<QByteArray> codecsNames( QTextCodec::availableCodecs() );

	comboBox->clear();

	foreach ( QByteArray name, codecsNames )
		comboBox->addItem(name);

}

int QyCodecDialog::exec() {

	fillComboBox(codecBox);

	return QDialog::exec();
}

void QyCodecDialog::keyPressEvent( QKeyEvent * event ) {

	int key = event->key(),
		modifiers = event->modifiers();

	if ( key == Qt::Key_Return && modifiers == Qt::NoModifier ) {
		close();
		emit codecChanged( codecBox->currentText() );
	} else if ( key == Qt::Key_Escape && modifiers == Qt::NoModifier )
		close();

}
